/**
* Copyright 2012 nabla
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package com.nabla.wapp.client.ui;

import java.util.Iterator;
import java.util.logging.Logger;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.user.client.ui.Widget;
import com.nabla.wapp.client.general.LoggerFactory;
import com.nabla.wapp.client.ui.form.Form;
import com.nabla.wapp.shared.signal.Signal;
import com.nabla.wapp.shared.slot.ISlot;
import com.nabla.wapp.shared.slot.ISlotManager;
import com.smartgwt.client.widgets.Window;


public class Dialog extends Window implements IHasWidgets {

	private static final Logger	log = LoggerFactory.getLog(Dialog.class);
	private static int			margin = Resource.bundle.style().DIALOG_DEFAULT_MARGIN();
	private final Signal			sigClose = new Signal();
	private final VLayout			layout = new VLayout();

	public Dialog() {
		this.setShowMaximizeButton(false);
		this.setShowMinimizeButton(false);
		this.setShowCloseButton(false);
		this.setDismissOnEscape(false);
		this.setAutoSize(true);
		layout.setMargin(1);
		layout.setLayoutMargin(margin);
		layout.setMembersMargin(0);
		layout.setEdgeImage("edge.png");
		layout.setEdgeSize(3);
		layout.setShowEdges(true);
		layout.setWidth("100%");
		layout.setHeight("100%");
		addItem(layout);
	}

	static public void setDefaultMargin(int value) {
		margin = value;
	}

    public void bind(final Form form) {
    	form.getSuccessSlots().connect(new ISlot() {
    		@Override
    		public void invoke() {
				Scheduler.get().scheduleDeferred(new ScheduledCommand() {
					@Override
					public void execute() {
						hide();
					}
				});
    		}
    	});
    }

	@Override
	public void add(final Widget w){
        Helper.add(layout, w);
	}

	@Override
	public void hide() {
		super.hide();
		sigClose.fire();
	}

	@Override
	public void clear() {}

	@Override
	public Iterator<Widget> iterator() {
        return null;
	}

	@Override
	public boolean remove(@SuppressWarnings("unused") final Widget w) {
		return false;
	}

	public ISlotManager getCloseSlots() {
		return sigClose;
	}

	public void setCaption(final String caption) {
		setTitle(caption);
	}

	public void setModal(final boolean isModal) {
		setIsModal(isModal);
	}

	public void setIcon(final String imgSrc) {
		log.fine("setting dialog icon to '" + imgSrc + "'");
		setHeaderIcon(imgSrc);
	}

}